// nutui
import { Button, Input, Toast } from "@nutui/nutui-react-taro";
import { Form } from "@nutui/nutui-react-taro";

// taro
import Taro, { useShareAppMessage } from "@tarojs/taro";
import { View } from "@tarojs/components";

// react
import { useEffect, useRef, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { changeUser, phoneOpenid, storeUser } from "@/redux/userSlice";


import {  ApiMemberInfo,  ApiSendCaptcha, ApiUpdateMemberMobile } from "../../utils/api";
import "./model.scss";

import WXBizDataCrypt from "../../../Node/WXBizDataCrypt";
import config from "../../../config/wx";

const phone = () => {
  useShareAppMessage((res) => {
    if (res.from === "button") {
      // 来自页面内转发按钮
      console.log(res.target);
    }

    return {
      title: "东进会员",
      path: "pages/home/index", //?id=123
      imageUrl: "../../assets/home.jpg",
      // imageUrl,
    };
  });
  // 表单控件
  const [form] = Form.useForm();
  const dispatch = useDispatch();

  // const storeMemberId = useSelector(storeMember_id);
  const user = useSelector(storeUser);
  const myOpenid = useSelector(phoneOpenid);

  const [registerForm, SetRegisterForm] = useState({
    openid: Taro.getStorageSync("openid") || "",
    sessionKey: Taro.getStorageSync("sessionKey") || "",
  });

  // 用户手机号等
  const [formData, setFormData] = useState({
    name: "",
    sex: 0,
    birthday: null,
    mobile: "",
    captcha: "",
    plate_number: "",
  });

  // 检查并登录的member_id
  const [member_id, setMember_id] = useState(-1);
  // 验证码
  const [sendCode, setSendCode] = useState(false);
  const [num, setNum] = useState(60);
  const [phone, setPhone] = useState("");
  // 修改user对象属性值
  const handleFieldChange = <K extends keyof RootObject>(
    fieldName: K,
    value: RootObject[K]
  ) => {
    // console.log(fieldName, value);
    setFormData((prevData) => ({
      ...prevData,
      [fieldName]: value,
    }));
  };

  //  user对象里的属性名 属性值
  const handleNameInputChange = (
    type: keyof RootObject,
    value: RootObject[keyof RootObject]
  ) => {
    // console.log("type", type);
    handleFieldChange(type, value);
    // console.log("formData", formData);
  };

  // 获取会员详情信息
  const getMemberInfo = async (member_id2?: number) => {
    let my_member_id = member_id2 ? member_id2 : member_id;
    // console.log(my_member_id, "my_member_id");
    if (!myOpenid) {
      console.log("需重新进入");
      // navigate("/");
      Taro.reLaunch({
        url: "/pages/home/index",
      });
      return;
    }
    // console.log(my_member_id, "my_member_id");
    // 请求用户信息

    // 校验是否有
    let resInfo;
    // console.log(user, "user");
    if (!user.mobile) {
      resInfo = await ApiMemberInfo(my_member_id);
      if (resInfo.code != 0) {
        console.log("请求用户信息失败");
        return;
      }
      // 没有请求,存仓库
      dispatch(changeUser(resInfo.data));
      const { mobile } = resInfo.data;
      // 更新
      setPhone(mobile);
    } else {
      // 从仓库读取
      // console.log(user, "user");
      // 更新用户对象
      const { mobile } = user;
      setPhone(mobile);
    }
    // form.setFieldsValue(formData);
    return resInfo;
  };

  // 确定注册手机
  const determine = async () => {
    //校验失败
    const flag = await handleMobileBlur(formData.mobile);
    if (!flag) {
      // form.submit();
      Taro.showToast({
        title: "手机号无效",
        icon: "error",
        duration: 1500,
      });
      return;
    }
    // console.log(formData, 2);
    if (formData.mobile == "") {
      Toast.show("test", { title: "请先填写手机号", duration: 1.5 });
      return;
    }
    // if (!isCodeSent) {
    //   // setSendCode(false);
    //   Toast.show("test", { title: "请先获取验证码", duration: 2 });
    //   return;
    // }
    if (formData.captcha == "") {
      Toast.show("test", { title: "请先填写验证码", duration: 1 });
      return;
    }
    if (phone == formData.mobile) {
      Toast.show("test", { title: "与原手机号一致", duration: 1.5 });
      return;
    }
    // 是否校验成功

    // Toast.show({ content: "校验失败" });
    console.log(formData.mobile, formData.captcha);
    // return;
    //校验成功
    try {
      const res = await ApiUpdateMemberMobile(
        formData.mobile,
        formData.captcha
      );
      // openToast("success", "修改手机号成功");
      // SetShowToast(true);
      if (res.code == 0) {
        Taro.showToast({
          title: "修改手机号成功",
          icon: "success",
        });
        dispatch(
          changeUser({
            ...user,
            mobile: formData.mobile,
          })
        );
        setTimeout(() => {
          Taro.reLaunch({
            url: "/pages/home/index",
          });
        }, 800);
      } else {
        Taro.showToast({
          title: res.msg,
          icon: "error",
        });
      }
      // navigate("/home");
      // Taro.reLaunch({
      //   url: "/pages/home/index",
      // });
    } catch (error: any) {
      // Toast.show({ content: error.msg || "验证码有误" });
      // Toast.show("fail", { title: error.msg || "验证码有误", duration: 2 });
      // openToast("fail", error.msg || "验证码有误");
      // SetShowToast(true);
      Taro.showToast({
        title: error.msg || "验证码有误",
        icon: "error",
      });
      // setSendCode(false);
    }
  };

  // 获取验证码
  // const handleSendCodeClick = async () => {
  //   // 获取原手机号
  //   //校验失败
  //   if (!isMobileValid) {
  //     Toast.show("test", { title: "手机号无效", duration: 2 });

  //     return;
  //   }
  //   if (phone == formData.mobile) {
  //     Toast.show("test", { title: "与原手机号一致", duration: 2 });

  //     return;
  //   }
  //   // 非空校验
  //   if (formData.mobile == "") {
  //     Toast.show("test", { title: "未输入手机号", duration: 2 });

  //     return;
  //   }
  //   // 校验
  //   try {
  //     await phoneValidator(null, formData.mobile);
  //     // 校验成功
  //   } catch (error) {
  //     // 校验失败
  //     return;
  //   }
  //   console.log("sendCode", sendCode);
  //   // 后续布置阿里云
  //   setSendCode(true);
  //   if (sendCode) {
  //     // 如果处于冷却状态，什么也不做
  //     console.log("sendCode", sendCode);
  //     return;
  //   }
  //   // 清除上一次的定时器
  //   clearInterval(timerRef.current as NodeJS.Timer);

  //   // 在这里处理发送验证码的逻辑
  //   // 获取手机号的值
  //   const res = await ApiSendCaptcha(formData.mobile);
  //   setIsCodeSent(true);
  //   // setSendCode(true)
  //   // 设置新的倒计时
  //   timerRef.current = setInterval(() => {
  //     setNum((prevNum) => {
  //       if (prevNum === 1) {
  //         clearInterval(timerRef.current as NodeJS.Timer);
  //         setSendCode(false);
  //         return num; // Reset the countdown
  //       }
  //       return prevNum - 1;
  //     });
  //   }, 1000);

  //   // 将新的定时器引用保存在 ref 中

  //   if (res.code == 0) {
  //     // handleNameInputChange("captcha", res.data.code);
  //     Toast.show({ content: "已发送", icon: "success" });
  //   }
  //   console.log("mobile:", formData.mobile);
  // };
  const handleSendCodeClick = async () => {
    // 获取原手机号
    //校验失败
    // if (!isMobileValid) {
    //   Toast.show("test", { title: "手机号无效", duration: 2 });
    //   return;
    // }

    if (phone == formData.mobile) {
      Toast.show("test", { title: "与原手机号一致", duration: 2 });
      return;
    }
    // 非空校验
    if (formData.mobile == "") {
      Toast.show("test", { title: "未输入手机号", duration: 2 });
      return;
    }
    //校验失败
    if (!(await handleMobileBlur(formData.mobile))) {
      // Toast.show("fail", { title: "手机号无效", duration: 2 });
      // openToast("fail", "手机号无效");
      // SetShowToast(true);
      Taro.showToast({
        title: "手机号无效",
        icon: "error",
      });
      // openToast("fail", "手机号无效");
      // SetShowToast(true);
      return;
    }
    // 校验
    try {
      await phoneValidator(null, formData.mobile);
      // 校验成功
    } catch (error) {
      // 校验失败
      return;
    }
    console.log("sendCode", sendCode);
    // 后续布置阿里云
    setSendCode(true);
    if (sendCode) {
      // 如果处于冷却状态，什么也不做
      console.log("sendCode", sendCode);
      return;
    }
    // 清除上一次的定时器
    clearInterval(timerRef.current as number);

    // 在这里处理发送验证码的逻辑
    // 获取手机号的值
    try {
      const res = await ApiSendCaptcha(formData.mobile);
      // setIsCodeSent(true);
      // setSendCode(true)
      // 设置新的倒计时
      timerRef.current = window.setInterval(() => {
        setNum((prevNum) => {
          if (prevNum === 1) {
            clearInterval(timerRef.current as number);
            setSendCode(false);
            return num; // Reset the countdown
          }
          return prevNum - 1;
        });
      }, 1000);

      // 将新的定时器引用保存在 ref 中

      if (res.code == 0) {
        handleNameInputChange("captcha", res.data.code);
        // Toast.show("success", { title: "已发送", duration: 2 });
        // openToast("success", "已发送");
        // SetShowToast(true);
        Taro.showToast({
          title: "已发送",
          icon: "success",
        });
      } else {
        // openToast("fail", res.msg || "发送失败");
        // SetShowToast(true);
        Taro.showToast({
          title: res.msg || "发送失败",
          icon: "error",
        });
      }
      console.log("mobile:", formData.mobile);
    } catch (error) {
      // openToast("fail", error.msg || "发送失败");
      // SetShowToast(true);
      Taro.showToast({
        title: error.msg || "发送失败",
        icon: "error",
      });
    }
  };

  // 在组件中添加 ref
  const timerRef = useRef<number | null>(null);
  // 在 useEffect 中清除上一次的定时器
  useEffect(() => {
    return () => {
      if (timerRef.current) {
        clearInterval(timerRef.current);
      }
    };
  }, []);

  // const [isCodeSent, setIsCodeSent] = useState(false); //是否发送了验证码
  // 校验手机号
  // const phoneValidator = (_, value, callback?) => {
  //   if (value) {
  //     let reg =
  //       /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
  //     // if (reg.test(value)) {
  //     //     handleNameInputChange("mobile", value);
  //     //     return callback();
  //     // }
  //     if (reg.test(value)) {
  //       handleNameInputChange("mobile", value);
  //       setIsMobileValid(true); // 设置手机号验证通过状态
  //       return Promise.resolve();
  //     }
  //     setIsMobileValid(false); // 设置手机号验证通过状态
  //     return Promise.reject(new Error("手机号无效"));
  //     // return Promise.reject(new Error("请输入11为数字手机号"));
  //   } else {
  //     // setIsMobileValid(false); // 设置手机号验证通过状态
  //     return Promise.reject(new Error("手机号不得为空"));
  //   }
  // };
  const phoneValidator = async (
    // FormItemRuleWithoutValidator
    ruleCfg: any,
    value: string
  ): Promise<string | boolean> => {
    if (value) {
      // console.log(value, "value");
      let reg =
        /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
      if (reg.test(value)) {
        handleNameInputChange("mobile", value);
        return Promise.resolve(""); // 空字符串表示验证通过
      }
      return Promise.reject("手机号无效"); // 字符串表示验证失败原因
    } else {
      return Promise.reject("手机号不得为空");
    }
  };

  // const getPhoneNumber = (res) => {
  //   // 获取手机号
  //   // https://api.weixin.qq.com/cgi-bin/token
  //   // https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=ACCESS_TOKEN
  //   console.log(0, res);
  //   // this.phone_code = res.detail.code // 获得的手机code
  //   // this.phone_encryptedData = res.detail.encryptedData //用于解密
  //   // this.phone_iv = res.detail.iv // 用于解密
  //   console.log(registerForm, "this.registerForm.sessionKey");
  //   var pc = new WXBizDataCrypt("wxa18cf1d233575f8c", registerForm.sessionKey);
  //   // console.log(pc, "pc");
  //   // console.log(res.encryptedData, "res.encryptedData");
  //   // console.log(res.encryptedIv, "res.encryptedIv");
  //   // var data = pc.decryptData(res.encryptedData, res.iv);
  //   if (!res.detail.encryptedData) {
  //     Toast.show("test", { title: "取消获取手机号" });
  //     return;
  //   }
  //   var data = pc.decryptData(res.detail.encryptedData, res.detail.iv);
  //   handleNameInputChange("mobile", data.phoneNumber);
  //   console.log("解密后 data:", data.phoneNumber);
  //   // 校验关闭
  //   phoneValidator(null, data.phoneNumber);
  //   form.resetFields();
  // };

  // 获取手机号
  // const getPhoneNumber = (res) => {
  //   // console.log(registerForm, "this.registerForm.sessionKey");
  //   const aid = config.config.aid;
  //   console.log(config, "config");

  //   console.log(res.detail, aid, registerForm.sessionKey);
  //   if (!res.detail.encryptedData) {
  //     console.warn(res.errMsg);
  //     return;
  //   }
  //   var pc = new WXBizDataCrypt(aid, registerForm.sessionKey);
  //   var data = pc.decryptData(res.detail.encryptedData, res.detail.iv);
  //   handleNameInputChange("mobile", data.phoneNumber);
  //   phoneValidator(null, data.phoneNumber);
  //   // console.log("解密后 data:", data.phoneNumber);
  // };

  // 获取手机号
  const getPhoneNumber = (res) => {
    // console.log(registerForm, "this.registerForm.sessionKey");
    const aid = config.config.aid;
    console.log(config, "config");

    console.log(res.detail, aid, registerForm.sessionKey);
    if (!res.detail.encryptedData) {
      console.warn(res.errMsg);
      return;
    }
    var pc = new WXBizDataCrypt(aid, registerForm.sessionKey);
    var data = pc.decryptData(res.detail.encryptedData, res.detail.iv);
    handleNameInputChange("mobile", data.phoneNumber);
    phoneValidator(null, data.phoneNumber);
    // console.log("解密后 data:", data.phoneNumber);
  };

  // 失去焦点
  // const handleMobileBlur = async (e) => {
  //   if (!isMobileValid) {
  //     Toast.show({ content: "手机号无效" });
  //     return;
  //   }
  //   const value = e.target.value;
  // };
  const handleMobileBlur = async (e) => {
    let reg =
      /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
    let flag;
    if (reg.test(e)) {
      handleNameInputChange("mobile", e);
      //  setIsMobileValid(true); // 设置手机号验证通过状态
      flag = true;
    } else {
      flag = false;
    }
    return flag;
    // console.log(e, 'e');
  };

  useEffect(() => {
    // 获取用户信息
    // getCode();
    // init();
    getMemberInfo();
    // 检测是否注册过
  }, []);

  // 更新界面
  // sendCode
  // 挂载页面
  useEffect(() => {
    form.setFieldsValue(formData);
  }, [formData, form]);

  return (
    <View>
      <Toast id="test" />
      {/* <Toast
        msg={state.msg}
        visible={showToast}
        type={state.type}
        onClose={() => {
          SetShowToast(false);
        }}
      /> */}
      <Form
        form={form}
        initialValues={{ ...formData }}
        divider
        labelPosition="left"
      >
        <Form.Item
          label="手机号"
          name="mobile"
          // rules={[{ max: 13, message: "请输入手机号" }]}
          rules={[{ validator: phoneValidator, required: true }]}
        >
          <View className="address">
            <Input
              placeholder="请输入新手机号"
              type="number"
              onBlur={handleMobileBlur}
              value={formData.mobile}
              onChange={(value) => handleNameInputChange("mobile", value)}
              // phoneValidator
            />
            <View className="box">
              <Button
                openType="getPhoneNumber"
                onGetPhoneNumber={getPhoneNumber}
                size="mini"
                className="btn"
              >
                获取手机号
              </Button>
              <span
                onClick={getPhoneNumber}
                className="phone_span my-component"
              >
                获取手机号
              </span>
            </View>
          </View>
        </Form.Item>
        <Form.Item label="验证码" name="captcha">
          <View className="address">
            <Input
              placeholder="请输入验证码"
              type="number"
              value={formData.captcha}
              onChange={(value) => handleNameInputChange("captcha", value)}
            />
            <View className="right my-component">
              <a
                onClick={handleSendCodeClick}
                style={{ display: sendCode ? "none" : "inline-block" }}
              >
                获取验证码
              </a>
              <span style={{ display: sendCode ? "inline-block" : "none" }}>
                {num}s后可重发
              </span>
            </View>
          </View>
        </Form.Item>
      </Form>
      <Form
        divider
        labelPosition="left"
        initialValues={{ ...formData }}
        // layout="horizontal"
        form={form}
        footer={
          <View>
            <Button
              // formType="submit"
              style={{
                backgroundColor: "#1677ff",
                border: "hsl(215, 100%, 84%)",
                width: "90vw",
                paddingTop: "3.3vh",
                paddingBottom: "3.3vh",
                fontSize: "4.8vw",
                marginTop: "2vh",
              }}
              block
              color="primary"
              size="large"
              onClick={determine}
            >
              确认
            </Button>
          </View>
        }
      ></Form>
    </View>
  );
};

export default phone;
